<template>
  <div class="profile-container">
    <div class="profile-header">
      <div class="user-info">
        <div class="avatar-container">
          <div class="user-avatar" @click="triggerAvatarUpload">
            <img v-if="avatar" :src="$http.defaults.baseURL.replace(/\/$/, '') + avatar" alt="用户头像" class="avatar-image">
            <span v-else>{{ username.charAt(0) }}</span>
          </div>
          <input ref="avatarInput" type="file" accept="image/*" @change="handleAvatarUpload" style="display: none">
          <div class="avatar-overlay" @click="triggerAvatarUpload">
            <span>修改头像</span>
          </div>
        </div>
        <div class="user-details">
          <h2>@{{ username }}</h2>
          <p class="post-count">{{ userPosts.length }} 篇帖子</p>
        </div>
      </div>
    </div>

    <div class="profile-tabs">
      <button class="tab-btn active">我的帖子</button>
    </div>

    <div class="posts-container">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="userPosts.length === 0" class="no-posts">
        <p>你还没有发布过任何帖子</p>
        <router-link to="/create" class="create-link">去发布第一篇帖子</router-link>
      </div>
      <div v-else class="posts-grid">
        <div v-for="post in userPosts" :key="post.id" class="post-card">
          <div class="post-header">
            <div class="user-info">
              <div class="avatar">
                <img v-if="post.userAvatar" :src="$http.defaults.baseURL + post.userAvatar" :alt="username" class="avatar-image">
                <span v-else>{{ username.charAt(0) }}</span>
              </div>
              <span class="username">@{{ username }}</span>
            </div>
          </div>
          
          <div class="post-images-preview" @click="goToPostDetail(post.id)">
            <img v-if="post.images && post.images.length > 0" :src="$http.defaults.baseURL.replace(/\/$/, '') + post.images[0]" alt="帖子图片" class="post-main-image">
            <img v-else-if="post.image" :src="$http.defaults.baseURL.replace(/\/$/, '') + post.image" alt="帖子图片" class="post-main-image">
            <div v-else class="no-image-placeholder">
              <span>📄</span>
            </div>
            <div v-if="post.images && post.images.length > 1" class="multi-image-indicator">
              📷 {{ post.images.length }}
            </div>
          </div>
          
          <div class="post-info">
            <h3 class="post-title">{{ post.title || '无标题' }}</h3>
            <p class="post-content">{{ post.content || '无内容' }}</p>
            <div class="post-meta">
              <span class="post-time">{{ formatDate(post.timestamp) }}</span>
              <div class="post-stats">
                <span class="likes">❤️ {{ post.likes || 0 }}</span>
              </div>
            </div>
          </div>
          
          <div class="post-actions">
            <button @click="editPost(post)" class="action-btn edit-btn">编辑</button>
            <button @click="deletePost(post.id)" class="action-btn delete-btn">删除</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑帖子模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <h3>编辑帖子</h3>
        <div class="form-group">
          <label>标题</label>
          <input v-model="editingPost.title" type="text" class="form-input" placeholder="请输入标题">
        </div>
        <div class="form-group">
          <label>内容</label>
          <textarea v-model="editingPost.content" class="form-textarea" placeholder="请输入内容"></textarea>
        </div>
        <div class="modal-actions">
          <button @click="saveEdit" class="save-btn">保存</button>
          <button @click="closeEditModal" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserProfile',
  data() {
    return {
      username: '',
      avatar: '',
      userPosts: [],
      loading: true,
      showEditModal: false,
      editingPost: {
        id: null,
        title: '',
        content: ''
      }
    }
  },
  async created() {
    this.username = localStorage.getItem('username') || '';
    this.avatar = localStorage.getItem('avatar') || '';
    await this.loadUserPosts();
  },
  methods: {
    async loadUserPosts() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          this.$router.push('/login');
          return;
        }

        const response = await this.$http.get(`/api/users/${userId}/posts`);
        this.userPosts = response.data;
      } catch (error) {
        console.error('加载用户帖子失败:', error);
        if (error.response?.status === 401) {
          this.$router.push('/login');
        } else {
          alert('加载失败，请重试');
        }
      } finally {
        this.loading = false;
      }
    },
    goToPostDetail(postId) {
      this.$router.push({ name: 'PostDetail', params: { id: postId } });
    },
    editPost(post) {
      this.editingPost = {
        id: post.id,
        title: post.title || '',
        content: post.content || ''
      };
      this.showEditModal = true;
    },
    async saveEdit() {
      if (!this.editingPost.title.trim() && !this.editingPost.content.trim()) {
        alert('标题和内容不能都为空');
        return;
      }

      try {
        const response = await this.$http.put(`/api/posts/${this.editingPost.id}`, {
          title: this.editingPost.title.trim(),
          content: this.editingPost.content.trim()
        });

        // 更新本地数据
        const index = this.userPosts.findIndex(post => post.id === this.editingPost.id);
        if (index !== -1) {
          this.userPosts[index] = { ...this.userPosts[index], ...response.data };
        }

        this.closeEditModal();
        alert('帖子更新成功');
      } catch (error) {
        console.error('更新帖子失败:', error);
        alert('更新失败，请重试');
      }
    },
    async deletePost(postId) {
      if (!confirm('确定要删除这篇帖子吗？此操作不可恢复。')) {
        return;
      }

      try {
        await this.$http.delete(`/api/posts/${postId}`);
        
        // 从本地列表中移除
        this.userPosts = this.userPosts.filter(post => post.id !== postId);
        
        alert('帖子删除成功');
      } catch (error) {
        console.error('删除帖子失败:', error);
        alert('删除失败，请重试');
      }
    },
    closeEditModal() {
      this.showEditModal = false;
      this.editingPost = {
        id: null,
        title: '',
        content: ''
      };
    },

    /* 触发头像上传 */
    triggerAvatarUpload() {
      this.$refs.avatarInput.click();
    },

    /* 处理头像上传 */
    async handleAvatarUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }

      // 验证文件大小（限制5MB）
      if (file.size > 5 * 1024 * 1024) {
        alert('图片大小不能超过5MB');
        return;
      }

      const formData = new FormData();
      formData.append('file', file);

      try {
        const token = localStorage.getItem('token');
        const response = await this.$http.post('/api/users/avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${token}`
          }
        });

        // 更新头像 - 使用相对路径，不包含baseURL
        const avatarUrl = response.data.avatar;
        this.avatar = avatarUrl;
        localStorage.setItem('avatar', avatarUrl);
        
        alert('头像更新成功');
        
        // 触发storage事件通知NavBar更新
        window.dispatchEvent(new Event('storage'));
        
        // 延迟刷新当前页面
        setTimeout(() => {
          window.location.href = window.location.pathname;
        }, 500);
      } catch (error) {
        console.error('头像上传失败:', error);
        alert('头像上传失败，请重试');
      }
    },
    formatDate(timestamp) {
      if (!timestamp) return '';
      try {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) return '刚刚';
        if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前';
        if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前';
        if (diff < 604800000) return Math.floor(diff / 86400000) + '天前';
        
        return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
      } catch (e) {
        return '';
      }
    }
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  background: white;
  border-radius: 10px;
  padding: 30px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-container {
  position: relative;
  width: 80px;
  height: 80px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  background: #ff2449;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32px;
  font-weight: bold;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
}

.avatar-overlay span {
  color: white;
  font-size: 12px;
  font-weight: bold;
  text-align: center;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-container:hover .user-avatar {
  transform: scale(1.05);
}

.user-details h2 {
  margin: 0 0 10px 0;
  color: #333;
}

.post-count {
  color: #666;
  margin: 0;
}

.profile-tabs {
  background: white;
  border-radius: 10px;
  padding: 0 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.tab-btn {
  background: none;
  border: none;
  padding: 15px 20px;
  margin-right: 20px;
  cursor: pointer;
  font-size: 16px;
  color: #666;
  border-bottom: 2px solid transparent;
}

.tab-btn.active {
  color: #ff2449;
  border-bottom-color: #ff2449;
}

.posts-container {
  min-height: 400px;
}

.loading {
  text-align: center;
  padding: 50px;
  color: #999;
}

.no-posts {
  text-align: center;
  padding: 50px;
  color: #999;
}

.create-link {
  color: #ff2449;
  text-decoration: none;
  margin-top: 10px;
  display: inline-block;
}

.posts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.post-card {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  transition: transform 0.2s ease;
}

.post-card:hover {
  transform: translateY(-2px);
}

.post-header {
  padding: 15px 15px 0 15px;
  display: flex;
  align-items: center;
}

.post-header .user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.post-header .avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff2449, #ff6b6b);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 14px;
  overflow: hidden;
}

.post-header .avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.post-header .username {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.post-images-preview {
  position: relative;
  width: 100%;
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}

.post-main-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image-placeholder {
  width: 100%;
  height: 100%;
  background: #f8f8f8;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32px;
  color: #ccc;
}

.multi-image-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
}

.post-info {
  padding: 15px;
}

.post-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.post-content {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.4;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.post-stats {
  display: flex;
  gap: 10px;
}

.post-actions {
  display: flex;
  border-top: 1px solid #f0f0f0;
}

.action-btn {
  flex: 1;
  background: none;
  border: none;
  padding: 12px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s ease;
}

.edit-btn {
  color: #1890ff;
}

.edit-btn:hover {
  background: #e6f7ff;
}

.delete-btn {
  color: #ff4d4f;
}

.delete-btn:hover {
  background: #fff1f0;
}

/* 编辑模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 10px;
  padding: 30px;
  width: 90%;
  max-width: 500px;
}

.modal-content h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  font-size: 14px;
}

.form-textarea {
  min-height: 100px;
  resize: vertical;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.save-btn {
  background: #52c41a;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.save-btn:hover {
  background: #389e0d;
}

.cancel-btn {
  background: #f0f0f0;
  color: #666;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn:hover {
  background: #e0e0e0;
}

@media (max-width: 768px) {
  .posts-grid {
    grid-template-columns: 1fr;
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
  }
}
</style>